from functools import wraps
from flask import g, request
from flask_login import current_user

from app.exceptions import handler
from .errors import forbidden, server_error


def permission_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        r = request
        local_uri = request.path
        url_rule = request.url_rule
        local_uri = url_rule.rule
        print(local_uri)
        method = request.method.upper()
        print(method)
        if not current_user.can(local_uri, method):
            return forbidden('Insufficient permissions')
        return func(*args, **kwargs)

    return decorated_view


def global_error_handler(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(e)
            message = handler(e)
            return server_error(message)
            pass

    return decorated_view
